import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { instance } from '..';
import { getCookie } from './../../utils/index';

export const registrationUser = createAsyncThunk(
  'products/registrationUser',
  async (userInfo, thunkAPI) => {
    try {
      const response = await instance.post(`/registration`, userInfo);
      return response;
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  },
);

export const loginUser = createAsyncThunk('products/loginUser', async (userInfo, thunkAPI) => {
  try {
    const response = await instance.post(`/login`, userInfo);
    return response;
  } catch (error) {
    return thunkAPI.rejectWithValue(error);
  }
});

const myCookieValueId = getCookie('id');

const initialState = {
  isAuth: !!myCookieValueId,
};

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    LogOut: (state, {payload}) => {
      state.isAuth = payload;
    },
    LogIn: (state, {payload}) => {
      state.isAuth = payload;
    },
    decrement: (state) => {
      state.count -= 1;
    },
    incrementByAmount: (state, action) => {
      state.count += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount, LogOut, LogIn } = authSlice.actions;

export default authSlice.reducer;
